<template>
  <div>
    <!-- 条件筛选 -->
    <div class="rt-header">
      <SearchForm ref="formWrapper" style="max-width:90%" :config="$attrs['search-config']" :import-config="$attrs['import-config']" :export-config="$attrs['export-config']" @onSubmit="onSubmit" @onReset="onReset" />
      <slot name="page-operations" />
    </div>
    <div v-loading="asyncData.showLoading && loading">
      <!-- 表格主体 -->
      <Table ref="tableWrapper" :config="$attrs['table-config']" :list="list" v-on="tableListeners">
        <template #header="{column}">
          <slot :name="column.prop+'_header'" />
        </template>
        <template #default="{row,column}">
          <slot :name="column.prop" :row="row" />
        </template>
      </Table>
      <!-- 分页 -->
      <Pagination
        :config="$attrs['pagination-config']"
        :page-index.sync="form.pageIndex"
        :total="total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        @custom-current-change="handleCustomCurrentChange"
      />
    </div>

  </div>
</template>

<script>
import SearchForm from './components/searchForm.vue'
import Table from './components/table.vue'
import Pagination from './components/pagination.vue'
export default {
  components: {
    SearchForm,
    Table,
    Pagination
  },
  inheritAttrs: false,
  props: {
    asyncData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      total: 0,
      form: {
        pageIndex: 1,
        pageSize: 10
      },
      list: [],
      loading: false
    }
  },
  computed: {
    _asyncData() {
      const defaultVal = {
        // 是否需要做初始化请求
        isInitial: true,
        // 列表数据异步请求api
        api: null,
        // api 请求参数
        query: {}
      }
      return Object.assign({}, defaultVal, this.asyncData)
    },
    tableListeners() {
      const that = this
      return {
        ...this.$listeners,
        'sort-change'(sortInfo) {
          const { order, prop } = sortInfo
          const orderMap = { descending: false, ascending: true }
          that.form[prop] = order ? orderMap[order] : null
          that.queryList()
        }
      }
    }
  },
  async created() {
    // 将条件搜索所有的表单默认值，映射到请求参数对象上
    const { formItems } = this.$attrs['search-config']
    if (Array.isArray(formItems) && formItems.length > 0) {
      const defQuery = formItems.reduce((accu, curr) => {
        const { prop, defaultVal } = curr
        if (defaultVal !== undefined) {
          accu[prop] = defaultVal
        }
        return accu
      }, {})
      this.form = { ...this.form, ...defQuery }
    }
    const { isInitial } = this._asyncData
    if (isInitial) {
      console.log('初始化请求', this.form)
      await this.queryList()
    }
  },
  methods: {
    onSubmit(search) {
      this.form = { ...this.form, ...search, pageIndex: 1 }
      this.queryList()
    },
    onReset(search) {
      this.form = { ...this.form, ...search, pageIndex: 1 }
      this.queryList()
    },
    // 使用element-ui pagination 组件进行分页
    handlePageChange(page) {
      this.form.pageIndex = page
      this.queryList()
    },
    // 使用上一页、下一页进行分页
    handleCustomCurrentChange(page) {
      this.form.pageIndex = page
      this.queryList()
    },
    handleSizeChange(size) {
      this.form.pageSize = size
      this.queryList()
    },
    assignParams() {
      const { query } = this._asyncData
      return {
        ...query,
        ...this.form
      }
    },

    getTable() {
      return this.$refs['tableWrapper'].$refs['el-table']
    },

    updateOptions(key, options) {
      const searchForm = this.$refs['formWrapper']
      if (!searchForm) {
        console.error('表单对象不存在')
        return
      }
      searchForm.updateOptions(key, options)
    },
    // 数据列表请求
    async queryList(queryParams = {}) {
      try {
        const { api, beforeQuery, cb } = this._asyncData
        this.form = Object.assign(this.form, queryParams)
        if (!api) return
        this.loading = true
        let query = this.assignParams()
        query = beforeQuery ? beforeQuery(query) : query
        const response = await api(query)
        const { result } = typeof cb === 'function' ? (cb(response) || {}) : response
        if (!result) return
        const { data, totalSize } = result
        this.list = data || []
        this.total = totalSize
        // 解决当前页数据被清空后，没有自动请求上一页数据的问题
        if (Array.isArray(data) && data.length === 0) {
          if (this.form.pageIndex >= 2) {
            this.form.pageIndex -= 1
            this.queryList()
          }
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    }

  }
}
</script>
<style lang="scss" scoped>
@mixin flex(
  $justify-content: center,
  $align-items: center,
  $flex-direction: row
) {
  display: flex;
  justify-content: $justify-content;
  align-items: $align-items;
  flex-direction: $flex-direction;
}
.rt-header {
  @include flex(space-between, flex-start);
  margin-bottom: 15px;
}
</style>
